<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标签名称" prop="tagName">
        <el-input
          v-model="queryParams.tagName"
          placeholder="请输入标签名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签类型" prop="tagType">
        <el-select v-model="queryParams.tagType" placeholder="请选择标签类型" clearable>
          <el-option v-for="item in tagTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col v-for="btn in actionButtons" :key="btn.text" :span="1.5">
        <el-button
          :type="btn.type"
          :plain="btn.plain"
          :icon="btn.icon"
          size="mini"
          :disabled="btn.disabled ? $data[btn.disabled] : false"
          @click="btn.handler"
          v-hasPermi="btn.permi"
        >{{ btn.text }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="park_tagsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="tagId" />
      <el-table-column label="标签名称" align="center" prop="tagName" />
      <el-table-column label="标签类型" align="center" prop="tagType">
        <template slot-scope="scope">
          <span>{{ getTagTypeLabel(scope.row.tagType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签图片" align="center" prop="tagImage" width="100">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.tagImage"
            :src="getFullImageUrl(scope.row.tagImage)" 
            style="width: 50px; height: 50px;"
            :preview-src-list="[getFullImageUrl(scope.row.tagImage)]">
          </el-image>
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:park_tags:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:park_tags:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改标签对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="标签类型" prop="tagType">
          <el-select v-model="form.tagType" placeholder="请选择标签类型">
            <el-option
              v-for="item in tagTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <template v-if="form.tagType !== undefined && form.tagType !== null">
            <div style="margin-top: 5px; color: #909399; font-size: 12px;">
              当前类型：{{ (tagTypeOptions.find(opt => opt.value === form.tagType) || {}).label || '未知' }}
            </div>
          </template>
        </el-form-item>
        <el-form-item label="标签图片" prop="tagImage">
          <EditImage
            v-model="form.tagImage"
            :cropper-config="{
              autoCrop: true,
              autoCropWidth: 64,
              autoCropHeight: 64,
              fixedBox: false,
              outputType: 'png'
            }"
            :dialog-width="'800px'"
            :cropper-height="400"
            upload-tip="支持 JPG、PNG 格式，建议尺寸 64x64，文件大小不超过 5MB"
            placeholder-text="请上传标签图片，建议尺寸 64x64 像素"
            cropper-title="园区标签图片裁剪"
            :max-file-size="5"
            @image-cropped="onImageCropped"
            @image-removed="onImageRemoved"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listPark_tags, getPark_tags, delPark_tags, addPark_tags, updatePark_tags, uploadPark_tagsFile } from "@/api/system/park_tags"
import EditImage from '@/components/EditImage/EditImage.vue'
import { BASE_FILE_URL, BASE_API } from '@/utils/constants'

export default {
  name: "Park_tags",
  components: { EditImage },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      park_tagsList: [],
      title: "",
      open: false,
      BASE_API: BASE_API, // 添加BASE_API到data中
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tagName: null,
        tagImage: null,
        tagType: 0,
        crateTimer: null,
        updateTimer: null
      },
      form: {},
      rules: {
        tagName: [
          { required: true, message: "标签名称不能为空", trigger: "blur" }
        ],
        tagType: [
          { required: true, message: "请选择标签类型", trigger: "change" }
        ]
      },
      croppedImageBlob: null,
      tagTypeOptions: [
        { label: "园区", value: 0 },
        { label: "仓库", value: 1 },
        { label: "行业", value: 2 },
        { label: "其他", value: 3 }
      ],
      actionButtons: [
        {
          text: "新增",
          type: "primary",
          plain: true,
          icon: "el-icon-plus",
          handler: function() { this.handleAdd() },
          permi: ['system:park_tags:add']
        },
        {
          text: "修改",
          type: "success",
          plain: true,
          icon: "el-icon-edit",
          handler: function() { this.handleUpdate() },
          disabled: "single",
          permi: ['system:park_tags:edit']
        },
        {
          text: "删除",
          type: "danger",
          plain: true,
          icon: "el-icon-delete",
          handler: function() { this.handleDelete() },
          disabled: "multiple",
          permi: ['system:park_tags:remove']
        },
        {
          text: "导出",
          type: "warning",
          plain: true,
          icon: "el-icon-download",
          handler: function() { this.handleExport() },
          permi: ['system:park_tags:export']
        }
      ]
    }
  },
  created() {
    // 绑定this到actionButtons的handler
    this.actionButtons.forEach(btn => {
      if (typeof btn.handler === "function") {
        btn.handler = btn.handler.bind(this)
      }
    })
    this.getList()
  },
  methods: {
    /** 标签类型显示 */
    getTagTypeLabel(type) {
      const found = this.tagTypeOptions.find(item => item.value === type)
      return found ? found.label : "未知"
    },
    /** 拼接服务器图片地址 */
    getFullImageUrl(imageUrl) {
      if (!imageUrl) return '';
      if (/^(http|https):\/\//.test(imageUrl) || imageUrl.startsWith('data:image/')) {
        return imageUrl;
      }
      if (imageUrl.startsWith('/')) {
        return this.BASE_API + imageUrl;
      }
      return BASE_FILE_URL + imageUrl;
    },
    /** 查询标签列表 */
    getList() {
      this.loading = true
      listPark_tags(this.queryParams).then(response => {
        this.park_tagsList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        tagId: null,
        tagName: null,
        tagImage: null,
        tagType: 0,
        crateTimer: null,
        updateTimer: null
      }
      this.croppedImageBlob = null
      this.resetForm && this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm && this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tagId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加标签"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const tagId = (row && row.tagId) || this.ids
      getPark_tags(tagId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改标签"
      })
    },
    /** 提交按钮 */
    async submitForm() {
      try {
        const valid = await this.$refs["form"].validate()
        if (!valid) return
        
        // 处理图片上传
        if (this.croppedImageBlob) {
          try {
            const formData = new FormData()
            formData.append('file', this.croppedImageBlob, 'park_tags.png')
            formData.append('type', 2) // 修改为数字类型
            const res = await uploadPark_tagsFile(formData)
            if (res && res.code === 200 && res.fileName) {
              this.form.tagImage = res.fileName || res.url
            } else {
              this.$modal.msgError("图片上传失败")
              return
            }
          } catch (e) {
            console.error('图片上传异常:', e)
            this.$modal.msgError("图片上传异常")
            return
          }
        }
        
        // 提交表单数据
        const action = this.form.tagId != null ? updatePark_tags : addPark_tags
        await action(this.form)
        this.$modal.msgSuccess(this.form.tagId != null ? "修改成功" : "新增成功")
        this.open = false
        this.getList()
      } catch (error) {
        console.error('提交失败:', error)
        this.$modal.msgError("提交失败: " + (error.message || '未知错误'))
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tagIds = (row && row.tagId) || this.ids
      this.$modal.confirm(`是否确认删除标签编号为"${tagIds}"的数据项？`).then(() => {
        return delPark_tags(tagIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download && this.download('system/park_tags/export', {
        ...this.queryParams
      }, `park_tags_${new Date().getTime()}.xlsx`)
    },
    // EditImage组件回调方法
    onImageCropped(blob, base64Url) {
      this.croppedImageBlob = blob
      console.log('图片裁剪完成:', blob, base64Url)
    },
    onImageRemoved() {
      this.croppedImageBlob = null
      console.log('图片已删除')
    }
  }
}
</script>

<style scoped lang="scss">
</style>
